<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.form-operator-button {
  background-color: #fff;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0;
  bottom: 50px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, .05);
}

.hex-form-inf {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  margin-right: 40px;
  position: relative;
  min-height: 33px;
  margin-left: 60px;
  line-height: 33px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}

.hex-form-inf-icon {
  font-size: 20px;
  margin-top: 5px;
  position: absolute;
  right: 0px;
}

.el-page-header__content {
  font-size: 14px;
}

.el-page-header__title {
  font-size: 14px;
}

.hex-form-inf .hex-form-inf-content-show {
  padding: 0 4%;
  background-color: gainsboro;
  border-radius: 8px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}
</style>

<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <div class="el-page-header__content"><b>用户列表</b></div>
        </div>
        <div>
          <!--工具栏-->
          <div class="head-container">
            <crudOperation :permission="permission"/>
          </div>

          <!--表格渲染-->
          <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;"
                    @selection-change="crud.selectionChangeHandler" @filter-change="crud.handleFilterChange"
                    :header-cell-style="{ background: 'rgba(52, 125, 225, 0.1)', color: '#404248' }" border stripe>
            <el-table-column :selectable="checkboxT" type="selection" width="55"/>
            <el-table-column v-if="columns.visible('username')" :show-overflow-tooltip="true" prop="username"
                             label="用户名"/>
            <el-table-column v-if="columns.visible('nickName')" :show-overflow-tooltip="true" prop="nickName"
                             label="姓名"/>
            <el-table-column v-if="columns.visible('sex')" prop="sex" label="性别"/>
            <el-table-column v-if="columns.visible('phone')" :show-overflow-tooltip="true" prop="phone" width="100"
                             label="电话"/>
            <el-table-column v-if="columns.visible('email')" :show-overflow-tooltip="true" width="125" prop="email"
                             label="邮箱"/>
            <el-table-column v-if="columns.visible('enabled')" key="enabled" label="状态" align="center" prop="enabled"
                             :filters="[{ text: '开启', value: true }, { text: '关闭', value: false }]"
                             filter-placement="bottom-end" :filter-multiple="false" column-key="enabled"
                             :filter-method="filterAgentStatus">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.enabled"
                  :disabled="user.id === scope.row.id"
                  active-color="#409EFF"
                  inactive-color="#F56C6C"
                  @change="changeEnabled(scope.row, scope.row.enabled)"

                />
              </template>
            </el-table-column>
            <el-table-column v-if="columns.visible('createTime')" :show-overflow-tooltip="true" prop="createTime"
                             width="140" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns.visible('operation')"
              v-permission="['admin','user:edit','user:del']"
              prop="operation"
              label="操作"
              width="210"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-col :xs="15" :sm="15" :md="15" :lg="15" :xl="15">
                  <udOperation :data="scope.row" :permission="permission" :disabled-dle="scope.row.id === user.id"/>
                </el-col>
                <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
                  <el-popover
                    popper-class="b-r-10"
                    placement="top"
                    width="180"
                    trigger="click"
                    :ref="'popover-' + `${scope.$index}`"
                  >
                    <p>确定要重置密码吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button
                        type="text"
                        size="mini"
                        @click="scope._self.$refs['popover-' + `${scope.$index}`].doClose()"
                      >取消
                      </el-button>
                      <el-button
                        type="primary"
                        size="mini"
                        @click="jxOrder(scope.row),scope._self.$refs['popover-' + `${scope.$index}`].doClose()"
                      >确定
                      </el-button>
                    </div>
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-key"
                      slot="reference">
                    </el-button>
                  </el-popover>
                </el-col>
              </template>
            </el-table-column>
          </el-table>

          <!--表单渲染-->
          <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                     :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="570px">
            <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model.trim="form.username"/>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model.number="form.phone"/>
              </el-form-item>
              <el-form-item label="姓名" prop="nickName">
                <el-input v-model.trim="form.nickName"/>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email"/>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex" style="width: 178px">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="form.enabled" :disabled="form.id === user.id">
                  <el-radio
                    v-for="item in dict.user_status"
                    :key="item.id"
                    :label="item.value"
                  >{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="margin-bottom: 0;" label="角色" prop="roles">
                <el-select
                  v-model="form.roles"
                  style="width: 437px"
                  multiple
                  filterable
                  placeholder="请选择"
                  @remove-tag="deleteTag"
                  @change="changeRole"
                >
                  <el-option
                    v-for="item in roles"
                    :key="item.name"
                    :disabled="level !== 1 && item.level <= level"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="crud.cancelCU">取消</el-button>
              <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import crudUser from '@/api/system/user'
import {isvalidPhone, validateUserName} from '@/utils/validate'
import {getDepts} from '@/api/system/dept'
import {getAll, getLevel} from '@/api/system/role'
import {getAllJob} from '@/api/system/job'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/extend/system/user/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import {mapGetters} from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

let userRoles = []
// crud交由presenter持有
const queryList = [{'cloumValue': 'blurry', 'cloumName': '姓名'}]
const defaultCrud = CRUD({
  title: '用户',
  url: 'api/users',
  queryList: queryList,
  crudMethod: {...crudUser},
  queryOnPresenterCreated: false,
})
const defaultForm = {
  id: null,
  username: null,
  nickName: null,
  sex: '男',
  email: null,
  enabled: 'false',
  roles: [],
  dept: {id: 1},
  job: {id: 10},
  phone: null
}
export default {
  name: 'User',
  components: {Treeselect, crudOperation, rrOperation, udOperation, pagination},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const validateContacts = (rule, value, callback) => {
      if (!validateUserName(value)) {
        callback(new Error('用户名不可输入中文字符'))
      } else {
        callback()
      }
    }

    var validateName = (rule, value, callback) => {
      if (value === '' || value === null || value.split(" ").join("").length == 0) {
        callback(new Error('请输入用户名称'));
      } else {
        setTimeout(() => {
          //用户名重复校验
          let param = {size: 1000000}
          crudUser.findListByPage(param).then(res => {
            let isExit = false
            res.content.forEach(item => {
              if ((item.id != this.crud.form.id) && (item.username === value)) {
                isExit = true
                if (isExit) {
                  callback(new Error('用户名称重复!'));
                }
              }
              if ((item.id != this.crud.form.id) && (item.email === value)) {
                isExit = true
                if (isExit) {
                  callback(new Error('邮箱名称重复!'));
                }
              }
            })
            callback();
          });
        }, 1000)
      }
    }
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      defaultProps: {children: 'children', label: 'name'},
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        {key: 'true', display_name: '激活'},
        {key: 'false', display_name: '锁定'}
      ],
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'},
          , {validator: validateName, trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
          {validator: validateName, trigger: 'blur'}
        ],
        phone: [
          {required: true, trigger: 'blur', validator: validPhone}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        enabled: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        roles: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.$nextTick(() => {
      this.getDeptDatas()
      this.crud.toQuery()
      this.crud.msg.add = '新增成功，默认密码：123456'
    })
  },
  mounted: function () {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    /* checkuserNicknameData(value, field) {
       let param = {};
       let result = false;
       //调用后台接口判断是否重复
       param[field] = value;
       param["pkId"] = this.form.pkId;
       crudUser.checkuserNicknameData(param).then(res => {
         if ('groupCode' === field) {
           this.validCodeStatus = res;
         } else {
           this.validNameStatus = res;
         }
       })
     },*/
    jxOrder(row) {
      crudUser.resetPass({username: row.username}).then(res => {
        this.$notify({
          title: '重置密码成功',
          type: 'success',
          duration: 2500
        })
      })
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function (data, index) {
        const role = {id: data}
        userRoles.push(role)
      })
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id)
      })
      crud.form.roles = initRoles
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (crud.findVM('form').$refs['form']) {
        crud.findVM('form').$refs['form'].clearValidate()
      }
      this.getDepts()
      this.getRoles()
      this.getRoleLevel()
      form.enabled = form.enabled.toString()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getJobs(1)
      userRoles = []
      const roles = []
      form.roles.forEach(function (role, index) {
        roles.push(role.id)
        // 初始化编辑时候的角色
        const rol = {id: role.id}
        userRoles.push(rol)
      })
      form.roles = roles
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {

      crud.form.roles = userRoles
      return true
    },
    // 获取左侧部门数据
    getDeptDatas() {
      const sort = 'id,desc'
      const params = {sort: sort}
      if (this.deptName) {
        params['name'] = this.deptName
      }
      getDepts(params).then(res => {
        this.deptDatas = res.content
      })
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({enabled: true}).then(res => {
        this.depts = res.content
      })
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudUser.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    // 获取弹窗内岗位数据
    getJobs(id) {
      getAllJob(id).then(res => {
        this.jobs = res.content
      }).catch(() => {
      })
    },
    // 点击部门搜索对应的岗位
    selectFun(node, instanceId) {
      this.getJobs(node.id)
      this.form.job.id = null
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    filterAgentStatus(value, row) {
      return row.enabled === value;
    },
    changeMenu() {
      this.$refs.form.validateField('deptid');
    },
  }
}
</script>

<style scoped>
</style>
